#!/usr/bin/env bash

# 引入外部脚本
. "${LINUX_TOOLS_DIR}/utils/utils.sh"
for f in ${LINUX_TOOLS_DIR}/scripts/docker/*.sh; do
  if [ "$f" != "${LINUX_TOOLS_DIR}/scripts/docker/docker.sh" ]; then
    source $f
  fi
done

application=""     #应用名称,docker ps中显示的名称
image=""           #docker仓库中镜像名称
applicationPath="" # 本地映射文件路径
port=""            #对外映射的端口号
passwd=""          # 密码
version=""         # 镜像版本号,默认为最新版本
dockerRunCmd=""    # 最后执行的docker run命令

# 在线安装Dockr
function docker_install_online() {
  echo -e "\n=========================开始安装docker - install docker start========================="
  echo_red "使用的官方脚本安装,可能因网络问题安装缓慢,请耐心等待============"

  curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun

  service docker start &>/dev/null
  sleep 2
  echo -e "\n=========================结束安装docker - install docker end=========================\n"
}

# 离线安装Dockr
function docker_install_offline() {
  echo -e "\n=========================开始安装docker - install docker start========================="
  dockerPath="/tmp"
    if which docker >/dev/null 2>&1; then
          docker_version=$(docker --version | grep -oE '[0-9]+\.[0-9]+' | head -n 1)
          major_version=${docker_version%%.*}
          minor_version=${docker_version##*.}
          systemctl start docker 2>&1 | tee -a "${CURRENT_DIR}"/install.log
          echo_red "==================docker已存在,无需安装=================="
    else
         if [ ! -f /tmp/docker.zip ]; then
            echo -e "[\033[31m ERROR \033[0m] 离线包不存在,尝试下载离线包"
            timeout 10 wget -qO docker.zip https://download.06171230.xyz/docker.zip || {
              rm -f ${dockerPath}/docker.zip
              echo -e "[\033[31m ERROR \033[0m] 下载失败 - Failed to download"
              echo -e "[\033[31m ERROR \033[0m] 请手动下载至/tmp文件夹下: https://download.06171230.xyz/docker.zip "
              exit 1
            }

         else

         command -v unzip &>/dev/null || install_soft unzip
         sleep 1
         unzip docker.zip

         chmod +x ${dockerPath}/docker/bin/*
         cp ${dockerPath}/docker/bin/* /usr/bin/
         cp ${dockerPath}/docker/service/docker.service /etc/systemd/system/
         chmod 754 /etc/systemd/system/docker.service
         mkdir -p /etc/docker/
         cp ${dockerPath}/docker/conf/daemon.json /etc/docker/daemon.json
         systemctl enable docker; systemctl daemon-reload; systemctl start docker 2>&1
         fi
    fi
  sleep 2
  echo -e "\n=========================结束安装docker - install docker end=========================\n"
}

function docker_update_registry() {
  echo_red "注意:修改镜像源会重启Docker服务,容器中所有服务都会停止,请确定是否修改!"

  read -r -p "请确定是否将镜像源修改为国内源!(y|n)：" input

  case $input in
  [yY][eE][sS] | [yY])
    mkdir -p /etc/docker
    cat >/etc/docker/daemon.json <<-EOF
    {
        "registry-mirrors": [
            "https://docker.1panel.live",
            "https://docker.mirrors.ustc.edu.cn"
        ]
    }
EOF
    systemctl daemon-reload
    sleep 1
    systemctl restart docker

    echo -e "\n镜像源修改成功!\n"

    ;;
  [nN][oO] | [nN]) ;;

  *)
    echo "请输入(Y/y|N/n)"
    exit
    ;;
  esac
}

# 判断是否删除已有容器
function docker_delExisting() {
  id=$(docker ps -a | grep $1 | awk '{print $1}')
  if [ "$id" != "" ]; then
    echo_yellow "\n建议删除已有容器,如果保留旧容器可能会出现冲突,导致创建失败!"
    echo_yellow "或者您可以修改脚本默认配置,来处理可能出现的冲突问题\n"
    read -r -p "发现docker中已存在$1容器,id:$id,请确认是否删除并重新安装!(y|n)：" input

    case $input in
    [yY][eE][sS] | [yY])
      echo -e "开始删除id=$id 的容器……"
      docker stop $id &>/dev/null
      docker rm $id &>/dev/null
      echo -e "删除成功！"
      ;;
    [nN][oO] | [nN])
      echo -e "您选择保留旧容器,请注意创建新容器时的名称及端口号,防止出现冲突!\n"
      ;;
    *)
      echo "请输入(Y/y|N/n)"
      exit
      ;;
    esac
  fi
}
# 输入版本号并拉取镜像
function docker_pull() {

  read -r -p "请输入$application镜像的版本(默认为${version})：" inputVersion
  if [ "$inputVersion" != "" ]; then
    version=$inputVersion
  fi

  if docker image inspect "$image:$version" &> /dev/null; then
      echo -e "\n镜像 $image:$version 存在,无需拉取"
  else
      echo_sleep "\n开始拉取$image:$version镜像,请等待……\n" 1
      docker pull ${image}:${version}
      if [ $? -eq 0 ]; then
        echo -e "\n镜像拉取成功！"
      else
        log_error "\n镜像拉取失败,请重试或确认 $image:$version 镜像是否存在！"
        exit
      fi
  fi
}
# 创建本地文件映射目录
function create_file_path() {
  rm -rf ${applicationPath}/*
  echo -e "开始创建映射到本机的目录:$@"
  for i in "$@"; do
    mkdir -p ${applicationPath}/$i &>/dev/null
    ls $applicationPath | grep $i &>/dev/null
    if [ $? -eq 0 ]; then
      echo -e "本地文件映射目录$i创建成功！"
      chmod -R 777 ${applicationPath}
    else
      echo -e "本地文件映射目录$i创建失败！"
      exit
    fi
  done

}
# 查看docker容器日志大小
function docker_log_size_show() {
  # 在执行过程中若遇到使用了未定义的变量或命令返回值为非零，将直接报错退出
  set -eu
  echo "================== ↓↓↓↓↓↓ 查询docker容器日志大小 ↓↓↓↓↓↓ ================"
  logs=$(find /var/lib/docker/containers/ -name '*-json.log*')

  for log in $logs; do
    ls -lh $log
  done
  echo "===================================================================="
}
# 安装Docker_compose
function install_docker_compose() {
  echo -e "\n=========================开始安装docker_compose - install docker_compose start========================="

  if [[ "" != $(command -v docker-compose) ]]; then
    echo_red "检测到 docker-compose 已安装,无需重复安装"
  else
    local composePath="/usr/local/bin/docker-compose" # 安装路径
    local version="v1.29.2"                           # 安装版本

    echo_red "使用gitee源安装,可能因网络问题安装缓慢或安装失败,请耐心等待或手动下载......"
    echo -e "\n采用安装包方式安装,版本默认为: ${version} ,开始下载......\n"

    timeout 120 curl -L "https://gitee.com/zangxw/docker-compose/releases/download/${version}/docker-compose-Linux-x86_64" -o ${composePath} || {
      rm -f ${composePath}
      echo -e "\n[\033[31m ERROR \033[0m] 下载失败,请手动下载安装 - Failed to download"
      echo -e "https://github.com/docker/compose/releases/download/${version}/docker-compose-$(uname -s)-$(uname -m)"

      exit 1
    }
    chmod +x ${composePath}

    ln -s ${composePath} /usr/bin/docker-compose

    if [[ "" == $(command -v docker-compose) ]]; then
      echo_red "安装 docker-compose 失败,请手动安装!"
      rm -f ${composePath}
    else
      echo_green "安装 docker-compose 成功!"

    fi
  fi

}

function docker_main() {
  clear
  echo_line "LINUX_TOOLS"
  echo -e "(1)  DockerCompose(包含大量常用应用,需要安装docker_compose)"
  echo -e "(2)  Mysql                  (3) Redis"
  echo -e "(4)  Nacos                  (5) Nginx"
  echo -e "(6)  Rocketmq               (7) ElasticSearch"
  echo -e "(8)  Kibana                 (9) LogStash"
  echo -e "(10) Frp                "
  echo -e ""
  echo -e "(94) docker_log_size_show(查看docker容器日志大小)"
  echo -e "(95) install_docker_compose(安装Docker_compose)"
  echo -e "(96) install_docker_offline(离线安装Docker)"
  echo -e "(97) install_docker_online(在线安装Docker)"
  echo -e "(98) update_registry(修改为国内源)"
  echo -e "(0)  Back(返回上一层菜单)"
  echo_line "LINUX_TOOLS"

  read -r -p "请输入要安装服务的编号(select)：" input
  case $input in
  1)
    docker_compose_linux
    break_end
    docker_main
    ;;
  2)
    mysql_install
    break_end
    docker_main
    ;;
  3)
    redis_install
    break_end
    docker_main
    ;;
  4)
    nacos_install
    break_end
    docker_main
    ;;
  5)
    nginx_install
    break_end
    docker_main
    ;;
  6)
    rocketmq_install
    break_end
    docker_main
    ;;
  7)
    elasticSearch_install
    break_end
    docker_main
    ;;
  8)
    kibana_install
    break_end
    docker_main
    ;;
  9)
    logStash_install
    break_end
    docker_main
    ;;
  10)
    frp_install
    break_end
    docker_main
    ;;
  94)
    docker_log_size_show
    break_end
    docker_main
    ;;
  95)
    install_docker_compose
    break_end
    docker_main
    ;;
  96)
    docker_install_offline
    break_end
    docker_main
    ;;
  97)
    docker_install_online
    break_end
    docker_main
    ;;
  98)
    docker_update_registry
    break_end
    docker_main
    ;;

  0)
    echo -e "返回上一层菜单"
    main
    ;;
  *)
    clear
    echo_red "请输入正确的编号，ctrl+c退出"
    sleep 1s
    docker_main
    ;;
  esac
}
